package com.atguigu.tingshu.search.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2024-04-09 15:15
 */
@Slf4j
@Component
public class SearchReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 监听专辑上架
     * 1.幂等性 ES 保存文档方法，保存或者更新
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ALBUM_UPPER)
    public void upperAlbum(ConsumerRecord<String, String> record) {
        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            log.info("[搜索服务]监听到专辑上架消息：{}", value);
            searchService.upperAlbum(Long.valueOf(value));
        }
    }


    /**
     * 监听专辑下架
     * 1.幂等性 ES 删除文档方法
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ALBUM_LOWER)
    public void lowerAlbum(ConsumerRecord<String, String> record) {
        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            log.info("[搜索服务]监听到专辑下架消息：{}", value);
            searchService.lowerAlbum(Long.valueOf(value));
        }
    }


    /**
     * 监听到声音/专辑统计消息
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void updateAlbumStat(ConsumerRecord<String, String> record) {
        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            log.info("[搜索服务]监听到更新声音统计信息消息：{}", value);
            TrackStatMqVo trackStatMqVo = JSON.parseObject(value, TrackStatMqVo.class);
            searchService.updateAlbumStat(trackStatMqVo);
        }
    }
}
